package org.jeecg.common.util.xinyuan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * MD5加密工具类
 *
 * @修改记录（修改时间、作者、原因）：
 */
public class MD5Util {

	private static String byteArrayToHexString(byte b[]) {  
        StringBuffer resultSb = new StringBuffer();  
        for (int i = 0; i < b.length; i++)  
            resultSb.append(byteToHexString(b[i]));  
  
        return resultSb.toString();  
    }  
  
    private static String byteToHexString(byte b) {  
        int n = b;  
        if (n < 0)  
            n += 256;  
        int d1 = n / 16;  
        int d2 = n % 16;  
        return hexDigits[d1] + hexDigits[d2];  
    }  
  
    public static String MD5Encode(String origin, String charsetname) {  
        String resultString = null;  
        try {  
            resultString = new String(origin);  
            MessageDigest md = MessageDigest.getInstance("MD5");  
            if (charsetname == null || "".equals(charsetname))  
                resultString = byteArrayToHexString(md.digest(resultString  
                        .getBytes()));  
            else  
                resultString = byteArrayToHexString(md.digest(resultString  
                        .getBytes(charsetname)));  
        } catch (Exception exception) {  
        }  
        return resultString;  
    }  
  
    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",  
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public static String createSign(Object obj,String APP_SECRET) {
        String jsonString = JSON.toJSONString(obj);
        String json = sortAsciiJson(jsonString,APP_SECRET);
        return Md5(json);
    }

    public static String Md5(String message) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        char[] charArray = message.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] digest = md5.digest(byteArray);
        StringBuilder sb = new StringBuilder();
        for (byte by : digest) {
            int var = by & 0xff;
            if (var < 16)
                sb.append("0");
            sb.append(Integer.toHexString(var));
        }
        return sb.toString();
    }

    private static String sortAsciiJson(String json, String APP_SECRET) {
        String res = "";
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            jsonObject.put("appSecret", APP_SECRET);
            Set<String> set = jsonObject.keySet();
            List<String> nameList = new ArrayList<>(set);
            Collections.sort(nameList);
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            for (int i = 0; i < nameList.size(); i++) {
                String name = nameList.get(i);
                String value = jsonObject.getString(name);
                if (i != 0) sb.append(",");
                if (value.startsWith("{") || value.startsWith("[")) {
                    sb.append(String.format("\"%s\":%s", name, value));
                } else {
                    sb.append(String.format("\"%s\":\"%s\"", name, value));
                }
            }
            sb.append("}");
            res = sb.toString();
        } catch (JSONException e) {
            return "";
        }
        return res;
    }

    private static final char hexDigits2[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String getMd5Code(String source) {
        String md5Value = null;

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source.getBytes("UTF-8"));
            // MD5 calculation is a 128-bit long integer, that is with 16-byte byte.
            byte tmp[] = md.digest();
            // Each byte expressed in hexadecimal using 2 characters, so that 32 bytes as hexadecimal.
            char str[] = new char[16 * 2];

            int k = 0; // The index of character in convert result.
            // Convert each byte to hexadecimal of MD5.
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits2[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits2[byte0 & 0xf];
            }
            // Convert the result from byte to string.
            md5Value = new String(str);
        } catch (Exception e) {
//            throw new MisException(e.getMessage(),e)/;
        }

        return md5Value;
    }
		 
}
